import React, { useEffect, useState, useRef } from 'react'
import { Breadcrumb, Table, Card, Switch, Button, Input, Modal, Form, message, Pagination, Select, Divider } from 'antd';
import { EditOutlined, DeleteOutlined, HeatMapOutlined, } from '@ant-design/icons'
import './UserList.scss'
import axios from '../utils/request'


const { Search } = Input;
const { Option } = Select;
const validateMessages = {
  required: '${label} is required!',
  types: {
    email: '${label} is not a valid email!',
    number: '${label} is not a valid number!',
  },
  number: {
    range: '${label} must be between ${min} and ${max}',
  },
};
export default function UserList() {
  // 初始化用户数据 
  const [userData, setUserData] = useState([])
  // 角色信息
  const [roleData, setRoleData] = useState([])
  // 添加弹窗状态 
  const [addIsModalVisible, setAddIsModalVisible] = useState(false);
  // 修改弹窗状态 
  const [editIsModalVisible, setEditIsModalVisible] = useState(false)
  // 添加表单引用
  let addFormRef = useRef(null)
  // 搜索 
  let [search, setSearch] = useState("")
  // 总条数
  let [total, setTotal] = useState(0)
  // 当前页
  let [page, setPage] = useState(1)
  // 每页条数 
  let [pageSize, setPageSize] = useState(2)
  // 修改信息回填
  const [editForm] = Form.useForm();

  /* 角色 */
  let [editRoleIsModalVisible, setEditRoleIsModalVisible] = useState(false)

  let [editRoleInfo, setEditRoleInfo] = useState({})

  // 初始化数据 
  useEffect(() => {
    setPage(1)
    getUserData()

  }, [search, page, pageSize])


  useEffect(() => {
    getRolesData()
  }, [])

  // 初始化角色数据 角色
  const getRolesData = async () => {
    let { data } = await axios.get("roles")
    setRoleData(data)
  }


  // 初始化请求数据 用户
  const getUserData = async () => {
    // console.log(pageSize);
    // console.log(search);
    // console.log(page);
    let { data } = await axios.get(`users?pagenum=${page}&query=${search}&pagesize=${pageSize}`)
    // console.log(data);
    if (data) {
      setTotal(data.total);
      setUserData(data.users);
    }
  }

  const columns = [
    {
      title: '姓名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: '角色',
      dataIndex: 'role_name',
      key: 'role_name',
    },
    {
      title: '状态',
      key: 'mg_state',
      render: (_, record) => {
        return (
          <Switch defaultChecked checked={record.mg_state} onChange={(e) => { onChangeSwitchHandle(e, record.id) }} />
        )
      }
    },
    {
      title: '操作',

      key: 'action',
      render: (_, record) => {
        return (
          <>
            <Button type="primary" size="small" onClick={() => { editShowModal(record) }}> <EditOutlined /> </Button> &nbsp;
            <Button type="primary" size="small" danger onClick={() => { delHandle(record.id) }} > <DeleteOutlined /> </Button> &nbsp;
            <Button type="primary" size="small" onClick={() => { editRoleShowModalHandle(record) }} style={{ backgroundColor: '#e6a23c', border: 'none' }} > <HeatMapOutlined /> </Button>
          </>
        )
      }

    }
  ];
  //  修改用状态 
  const onChangeSwitchHandle = async (state, id) => {
    let { data, meta } = await axios.put(`users/${id}/state/${state}`)
    console.log(data, meta,'修改状态');
    switch (meta.status) {
      case 200:
        message.success(meta.msg)
        break;

      default:
        message.error('修改状态失败')
        break;
    }
    getUserData()
  };

  // 搜索 
  const onSearch = (val) => {
    setSearch(val)
  }
  // 删除 
  const delHandle = async (id) => {
    let { meta } = await axios.delete(`users/${id}`)

    switch (meta.status) {
      case 200:
        message.success(meta.msg)
        break;
      default:
        message.warning("删除失败")
        break;
    }
    // 格式化数据 
    getUserData()
  }

  // 添加
  const layout = { labelCol: { span: 4 }, wrapperCol: { span: 20 } };

  // 添加接口请求 
  const onFinishAddHandle = async (userInfo) => {
    let { meta } = await axios.post('users', userInfo)
    switch (meta.status) {
      case 201:
        message.success(meta.msg)
        break;
      default:
        message.warning("添加失败")
        break;
    }
    // 将数据清空
    addFormRef.current.resetFields();
    // 窗口关闭 
    setAddIsModalVisible(false);
    // 将页面刷新 
    getUserData()
  };
  //展示
  const addShowModal = () => {
    setAddIsModalVisible(true);
  };
  // 添加取消 
  const addHandleCancel = () => {
    addFormRef.current.resetFields();
    setAddIsModalVisible(false);
  };

  let [editId, setEditId] = useState(null)
  /* 修改数据 */
  const onFinishEditHandle = async (val) => {
    let { meta } = await axios.put(`users/${editId}`, val)

    switch (meta.status) {
      case 200:
        message.success(meta.msg)
        break;

      default:
        message.info('更新数据失败！')
        break;
    }

    setEditIsModalVisible(false)
    getUserData()
  }



  // 修改弹窗关闭
  const editHandleCancel = () => {
    setEditIsModalVisible(false)
  }

  const editShowModal = (record) => {
    setEditIsModalVisible(true)
    // 修改数据回填
    editForm.setFieldsValue({
      username: record.username,
      email: record.email,
      mobile: record.mobile
    });

    setEditId(record.id)
  }
  // 分页
  const onChange = (page, pageSize) => {
    setPage(page)
    setPageSize(pageSize)
  }


  // 修改弹窗展示 
  const editRoleShowModalHandle = (record) => {
    setEditRoleIsModalVisible(true)
    setEditRoleInfo(record)
  }
  let [rid, setRid] = useState(null)
  // 修改弹窗关闭 
  const editRoleCancelHandle = () => {

    setEditRoleIsModalVisible(false)
  }
  // 修改角色下拉选中事件 
  const onChangeRoleHandle = async (rid) => {
    setRid(rid)
  }

  const editRolehandleOk = async () => {
    let { meta } = await axios.put(`users/${editRoleInfo.id}/role`, { rid })
    setEditRoleIsModalVisible(false)
    // console.log(meta);
    switch (meta.status) {
      case 200:
        message.success(meta.msg)
        break;

      default:
        message.error("修改角色失败！")
        break;
    }
    getUserData()
  }
  return (
    <div className='user-box'>
      {/* 头部面包屑区域 */}
      <Breadcrumb separator='>'>
        <Breadcrumb.Item href='/#/layout/home'>首页</Breadcrumb.Item>
        <Breadcrumb.Item>商品管理</Breadcrumb.Item>
        <Breadcrumb.Item>商品列表</Breadcrumb.Item>
      </Breadcrumb>
      <Divider />
      {/* 主体表格区域 */}
      <Card >
        <Search allowClear placeholder="input search text" onSearch={onSearch} enterButton style={{ width: 300, height: 60 }} />
        &nbsp;
        <Button type="primary" onClick={addShowModal} > <EditOutlined /> 添加用户 </Button>
        <Table pagination={false} bordered dataSource={userData} columns={columns} rowKey={(record) => record.id} />

        {/* 分页 */}
        <Pagination
          className='pagination'
          total={total}
          showSizeChanger
          showQuickJumper
          pageSizeOptions={[2, 4, 6]}
          defaultPageSize={2}
          showTotal={(total) => `一共 ${total} 条`}
          onChange={onChange}
        />
      </Card>
      {/* 添加区域表单 */}
      <Modal footer={null} title="信息添加" visible={addIsModalVisible} onCancel={addHandleCancel}>
        <Form {...layout} name="nest-messages" onFinish={onFinishAddHandle} validateMessages={validateMessages} ref={addFormRef}>
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[{ type: 'email' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item name='mobile' label="手机号">
            <Input />
          </Form.Item>

          <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 16 }}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
            &nbsp;
            <Button type="primary" onClick={() => { (addHandleCancel()) }} danger>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改区域表单 */}
      <Modal footer={null} title="信息修改" visible={editIsModalVisible} onCancel={editHandleCancel}>
        <Form {...layout} form={editForm} name="edit-messages" onFinish={onFinishEditHandle} validateMessages={validateMessages}>
          <Form.Item
            name="username"
            label="用户名">
            <Input disabled />
          </Form.Item>

          <Form.Item name="email" label="邮箱" rules={[{ type: 'email', required: true }]} >
            <Input />
          </Form.Item>

          <Form.Item name='mobile' label="手机号" rules={[{ required: true }]}>
            <Input />
          </Form.Item>

          <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 16 }}>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
            &nbsp;
            <Button type="primary" onClick={() => { editHandleCancel() }} danger>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      {/* 分配角色区域 */}
      <Modal title="角色分配" visible={editRoleIsModalVisible} onOk={editRolehandleOk} onCancel={editRoleCancelHandle}>
        <p> 当前用户: <b> {editRoleInfo.username} </b> </p>
        <p> 当前角色: <b> {editRoleInfo.role_name} </b> </p>
        分配角色: &nbsp;
        <Select placeholder="请选择角色" onChange={onChangeRoleHandle} style={{ width: '200px' }}>
          {
            roleData.map(item => {
              return (
                <React.Fragment key={item.id}>
                  <Option value={item.id}>{item.roleName}</Option>
                </React.Fragment>
              )
            })
          }
        </Select>
      </Modal>
    </div>
  )
}
